<template>
  <el-card shadow="hover" class="patient-list-card">
    <!-- 搜索区 -->
    <div class="search-area flex items-center mb-4 space-x-2">
      <el-input
          v-model="keyword"
          placeholder="搜索患者…"
          clearable
          size="medium"
          prefix-icon="el-icon-search"
          class="flex-1"
          @keyup.enter.native="load"
      />
      <el-button type="primary" icon="el-icon-refresh" size="medium" @click="load">
        刷新
      </el-button>
    </div>

    <!-- 本人 / 科室 Tab -->
    <el-tabs
        v-model="scope"
        type="border-card"
        class="mb-4"
        @tab-click="load"
    >
      <el-tab-pane label="本人" name="my" />
      <el-tab-pane label="科室" name="dept" />
    </el-tabs>

    <!-- 未诊 / 已诊 折叠面板 -->
    <el-collapse v-model="opened" accordion>
      <el-collapse-item title="未诊患者" name="todo">
        <el-scrollbar wrap-style="{ maxHeight: '240px' }">
          <el-empty
              v-if="todo.length === 0"
              description="暂无未诊患者"
          />
          <template v-else>
            <div
                v-for="p in todo"
                :key="p.id"
                class="p-item flex justify-between"
                @dblclick="select(p)"
            >
              <span class="font-medium">{{ p.realname }}</span>
              <span class="text-gray-500">{{ p.casenumber }}</span>
            </div>
          </template>
        </el-scrollbar>
      </el-collapse-item>

      <el-collapse-item title="已诊患者" name="done">
        <el-scrollbar wrap-style="{ maxHeight: '240px' }">
          <el-empty
              v-if="done.length === 0"
              description="暂无已诊患者"
          />
          <template v-else>
            <div
                v-for="p in done"
                :key="p.id"
                class="p-item flex justify-between"
                @dblclick="select(p)"
            >
              <span class="font-medium">{{ p.realname }}</span>
              <span class="text-gray-500">{{ p.casenumber }}</span>
            </div>
          </template>
        </el-scrollbar>
      </el-collapse-item>
    </el-collapse>
  </el-card>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'

const emit = defineEmits(['select'])

// 从 Pinia 拿到当前医生 ID
const counterStore = useCounterStore()
const doctorId     = computed(() => counterStore.userId)

// 搜索关键字、Tab 模式、折叠面板状态
const keyword = ref('')
const scope   = ref('my')
const opened  = ref(['todo'])

// 患者列表数据
const todo = ref([])
const done = ref([])

// 科室 ID（当 scope 为 dept 时使用）
const deptId = ref(null)

async function fetchDoctorInfo() {
  if (!doctorId.value) return
  const { data } = await axios.get('/api/doctor/info', {
    headers: { 'X-User-Id': doctorId.value }
  })
  deptId.value = data.deptId
}

async function load() {
  if (!doctorId.value) return

  if (scope.value === 'dept' && deptId.value == null) {
    await fetchDoctorInfo()
  }

  const base = { mode: scope.value, kw: keyword.value }
  const paramsTodo = {
    ...base,
    type: 'unseen',
    ...(scope.value === 'my'
        ? { userid: doctorId.value }
        : { deptid: deptId.value })
  }
  const paramsDone = { ...paramsTodo, type: 'seen' }

  const [unRes, seRes] = await Promise.all([
    axios.get('/api/doctor/patients', {
      params:   paramsTodo,
      headers:  { 'X-User-Id': doctorId.value }
    }),
    axios.get('/api/doctor/patients', {
      params:   paramsDone,
      headers:  { 'X-User-Id': doctorId.value }
    })
  ])

  todo.value = unRes.data.records || unRes.data.data || []
  done.value = seRes.data.records || seRes.data.data || []
}

const select = p => emit('select', p)

watch([doctorId, keyword, scope], () => {
  opened.value = ['todo']
  load()
}, { immediate: true })

onMounted(load)
</script>

<style scoped>
.patient-list-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
}
.search-area {
  display: flex;
  align-items: center;
}
.p-item {
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.p-item:hover {
  background-color: #ecf5ff;
}
</style>
